#define DEBUG
#include <cstdio>

using namespace std;

const int maxn=100000, maxk=17;

int up[maxn+1][maxk+1], dep[maxn+1], root[maxn+1], dia[maxn+1][2];

int max(int a, int b) {
  return a>b ? a : b;
}

void update(int o, int fa) {
  if (fa) {
    root[o] = root[fa];
  } else {
    root[o] = o;
    dia[o][0] = dia[o][1] = o;
  }
  dep[o] = dep[fa]+1;
  up[o][0] = fa;
  for (int i=1; i<=maxk; i++) {
    up[o][i] = up[up[o][i-1]][i-1];
  }
}

int lca(int u, int v) {
  int ret;
  if (dep[u]<dep[v]) {
    ret = u, u = v, v = ret;
  }
  ret = 0;
  for (int i=maxk; i>=0; i--) {
    if (dep[up[u][i]]>=dep[v]) {
      ret += 1<<i;
      u = up[u][i];
    }
  }
  if (u==v) {
    return ret;
  }
  for (int i=maxk; i>=0; i--) {
    if (up[u][i]!=up[v][i]) {
      ret += 2<<i;
      u = up[u][i], v = up[v][i];
    }
  }
  return ret+2;
}

int main() {
  freopen("newbarn.in", "r", stdin);
  freopen("newbarn.out", "w", stdout);

  int q, n=0;
  scanf("%d", &q);
  for (int i=1; i<=q; i++) {
    char c;
    int p;
    scanf(" %c %d", &c, &p);
    if (c=='B') {
      update(++n, max(p, 0));
      int x=dia[root[n]][0], y=dia[root[n]][1], a=lca(n, x), b=lca(n, y), c=lca(x, y);
      if (a>=b & a>=c) {
        dia[root[n]][1] = n;
      } else if (b>=a && b>=c) {
        dia[root[n]][0] = n;
      }
    } else {
      int x=dia[root[p]][0], y=dia[root[p]][1];
      printf("%d\n", max(lca(p, x), lca(p, y)));
    }
  }

  fclose(stdin);
  fclose(stdout);
  return 0;
}
